// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import EventManager from './EventManager'
import GameMgr from './GameManager'

const { ccclass, property } = cc._decorator

@ccclass
export default class ToastManager extends cc.Component {
  duration: number = 0.15
  // 定义Toast的起始位置
  outOfWorld = cc.v2(0, 0)
  // 定义淡入动画
  actionFadeIn = null
  // 定义淡出动画
  actionFadeOut = null
  // 标题
  _title: cc.Label = null
  // 按钮文字
  _btn_label: cc.Label = null
  // 按钮回调函数
  _btn_callback = null
  onLoad() {
    this.node.active = false
    this.node.position.x = this.outOfWorld.x
    this.node.position.y = this.outOfWorld.y
    this.actionFadeIn = cc
      .tween(this.node)
      .to(this.duration, { opacity: 255, scale: 1.0 })
      .call(() => {
        this.fadeInCallback()
      })
    this.actionFadeOut = cc
      .tween(this.node)
      .to(this.duration, { opacity: 0, scale: 1.5 })
      .call(() => {
        this.node.active = false
        this.fadeOutCallback()
      })
    this.node.on('fade-in', this.startFadeIn, this)
    this.node.on('fade-out', this.startFadeOut, this)
    EventManager.on('ToastClick', this.toastClicked, this)
  }
  toastClicked() {
    console.log('我被点击了')
    this.node.emit('fade-out')
  }
  startFadeIn({ title, btntext, callback }) {
    this.node.active = true
    this.node.position = cc.v3(0, 0, 0)
    this.node.setScale(2.0)
    this.node.opacity = 0
    this.actionFadeIn.start()
    this.initContent(title, btntext)
    this._btn_callback = callback
  }
  initContent(title, btntext) {
    this._title = this.node.getChildByName('title_label').getComponent(cc.Label)
    let toast_btn = this.node.getChildByName('toast_btn')
    this._btn_label = toast_btn.getChildByName('Background').getChildByName('toast_btnlabel').getComponent(cc.Label)
    this._title.string = title
    this._btn_label.string = btntext
    // GameMgr.instance.utils.addClickEvent(toast_btn, this.node, 'Toast', 'onClick')
  }
  fadeInCallback() {}

  fadeOutCallback() {
    this.node.setPosition(this.outOfWorld.x, this.outOfWorld.y)
  }

  startFadeOut() {
    if (typeof this._btn_callback === 'function') {
      this._btn_callback()
    }
    this.actionFadeOut.start()
    this._title.string = ''
    this._btn_label.string = ''
    this._btn_callback = null
  }
}
